package com.theaf.core.repo.kit;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

/**
 * 排序构造
 */
public class SimpleSortBuilder {

    /**
     * 调用的时候使用SimpleSortBuilder.generateSort(map);
     */
    public static Sort generateSort(Map<String,Boolean> map) {
        if(map==null||map.size()==0){
            return null;
        }
        List<Order> orders = new ArrayList<Order>();
        for(String f:map.keySet()) {
            Order order = null;
            if(!map.get(f)) {
                order = new Order(Direction.DESC,f);
            } else {
                order = new Order(Direction.ASC,f);
            }
            orders.add(order);
        }
        return new Sort(orders);
    }

    public static Sort generateSort(String... fields) {
        List<Order> orders = new ArrayList<Order>();
        for(String f:fields) {
            Order order = null;
            String ff[] = f.split("_");
            if(ff.length==2&&ff[1].equalsIgnoreCase("d")) {
                order = new Order(Direction.DESC,ff[0]);
            } else {
                order = new Order(Direction.ASC,ff[0]);
            }
            orders.add(order);
        }
        return new Sort(orders);
    }

}
